//
//  IfengMenuItemCell.m
//  IfengNews
//
//  Created by Ryan on 13-7-12.
//
//

#import "IfengMenuItemCell.h"
#import <QuartzCore/QuartzCore.h>
#import "CLGloble.h"

#define IfengMenuItemCellSize 11.f
@interface IfengMenuItemCell ()

@property (nonatomic,strong) UILabel *lable;
@property (nonatomic,strong) UIImageView *moveBGImageView;
@property (nonatomic,strong) UIColor *boderColor;
@property (nonatomic,strong) UILabel *textLabel;
@property (nonatomic,weak) id<NSObject> tapDelegate;
@property (nonatomic,assign) SEL tapSel;
@property (nonatomic,assign) CGPoint startOffset;
@property (nonatomic,strong) UITapGestureRecognizer *tap;
@property (nonatomic,strong) UIPanGestureRecognizer *panGr;

@property (nonatomic,assign) NSTimeInterval lastMoveTime;// 上次移动的时间
@property (nonatomic,strong) NSTimer *moveTimer; // 计时开始调整位置



- (void)_invokePan:(UIPanGestureRecognizer *)sender;
- (void)_timerAction:(NSTimer *)timer;

@end

@implementation IfengMenuItemCell

- (id)initWithBoderColor:(UIColor *)color{
    self = [super init];
    if(self){

        self.isblank=NO;
      self.boderColor=color;
      self.userInteractionEnabled = YES;
      
      _tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(invokeTap)];
      _panGr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(_invokePan:)];
      
      [_tap requireGestureRecognizerToFail:_panGr];
      
      [self addGestureRecognizer:_tap];
      [self addGestureRecognizer:_panGr];
    }
    return self;
}

- (void)dealloc{
    _panGr = nil;
    _moveTimer = nil;
    _moveBGImageView = nil;
}

- (void)reInitCompont{
    if(self.isblank)return;
    self.crashTestRect = CGRectInset(self.frame, INSET_X, INSET_Y);
//    CALayer *line=[CALayer layer];
//    line.frame=CGRectInset(self.bounds, 0.5, 0.5);
//    [self.layer addSublayer:line];
//    line.borderColor=[RGB(0x6c, 0x6c, 0x6c) colorWithAlphaComponent:0.5].CGColor;
//    line.borderWidth=0.5;
    
    
//    [self.layer setBorderWidth:0.5f];
//    //[self.layer setBounds:self.bounds];
//    [self.layer setBorderColor:[RGB(0x6c, 0x6c, 0x6c) colorWithAlphaComponent:0.5].CGColor];
  
  _moveBGImageView = [[UIImageView alloc] init];
  _moveBGImageView.frame = CGRectMake(0, 0, 68, 32);
  _moveBGImageView.image = [UIImage imageNamed:@"order_gray.png"];
  //_moveBGImageView.alpha = 0;
  [self addSubview:_moveBGImageView];
  
    self.textLabel=[UILabel new];
    self.textLabel.frame=self.bounds;
 
    self.textLabel.font=[UIFont systemFontOfSize:IfengMenuItemCellSize];
    self.textLabel.textColor=RGB(0x6e, 0x6e, 0x6e);
    self.textLabel.textAlignment=NSTextAlignmentCenter;
    self.backgroundColor = [UIColor whiteColor];
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.autoresizesSubviews = YES;
    [self addSubview:self.textLabel];
}

- (void)setStaticYES{
    self.textLabel.textColor=[UIColor redColor];
   // self.layer.borderColor=self.textLabel.textColor.CGColor;
    _moveBGImageView.image = [UIImage imageNamed:@"order_red.png"];
    [self removeGestureRecognizer:self.tap];
    [self removeGestureRecognizer:self.panGr];

}

- (void)setLockArea{
    self.isLockArea=YES;
     //self.textLabel.textColor=[UIColor purpleColor];
}

- (void)setText:(NSString *)itemTitle{
    if(self.isblank || _isStrNULL(itemTitle))return;
    if([itemTitle length]<4){
        self.textLabel.frame=self.bounds;
        self.textLabel.font=[UIFont systemFontOfSize:IfengMenuItemCellSize];
        self.textLabel.numberOfLines=1;
       
    }else{
        CGRect frame=self.bounds;
        frame.size.width=frame.size.width-20;
        frame.origin.x=10;
        self.textLabel.frame=frame;
        self.textLabel.font=[UIFont systemFontOfSize:IfengMenuItemCellSize];
        self.textLabel.numberOfLines=1;

    }
     self.textLabel.text=itemTitle;
}

- (void)invokeTap{
    if(self.isblank)return;
    if(self.tapDelegate && self.tapSel){
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self.tapDelegate performSelector:self.tapSel withObject:self];
#pragma clang diagnostic pop
    }
}

- (void)_invokePan:(UIPanGestureRecognizer *)sender{
    if(self.isblank)return;
  switch (sender.state) {
    case UIGestureRecognizerStateBegan:{
      self.lastMoveTime = [NSDate timeIntervalSinceReferenceDate];
      CGPoint beginPosition = [sender locationInView:self.superview];
      self.startOffset = CGPointMake(self.center.x-beginPosition.x, self.center.y-beginPosition.y);
      [self.superview bringSubviewToFront:self];
    //  _moveBGImageView.alpha = 1.0;
      break;
    }
    case UIGestureRecognizerStateChanged:{
      CGPoint currentPosition = [sender locationInView:self.superview];
      //      NSLog(@"------%f",fabsf((currentPosition.x+self.startOffset.x) - self.center.x));
      if (fabsf((currentPosition.x+self.startOffset.x) - self.center.x) > TRIGGER_MIN_DRIFT || fabsf((currentPosition.y+self.startOffset.y) - self.center.y) > TRIGGER_MIN_DRIFT) {
        // 停一段时间再触发。先弃置，性能什么的出问题再说
        //        if ([NSDate timeIntervalSinceReferenceDate] - self.lastMoveTime < 0.01) {
        //          if ([_moveTimer isValid]) {
        //            [_moveTimer invalidate];
        //            self.moveTimer = nil;
        //          }
        //        }
        //        if (!_moveTimer) {
        //          self.moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.012 target:self selector:@selector(_timerAction:) userInfo:nil repeats:NO];
        //        }
        [self _timerAction:_moveTimer];
      }
      self.center = CGPointMake(currentPosition.x+self.startOffset.x, currentPosition.y+self.startOffset.y);
      self.lastMoveTime = [NSDate timeIntervalSinceReferenceDate];
      break;
    }
    case UIGestureRecognizerStateEnded:
    case UIGestureRecognizerStateFailed:
    case UIGestureRecognizerStateCancelled:
    case UIGestureRecognizerStatePossible:{
      self.startOffset = CGPointZero;
    //  _moveBGImageView.alpha = 0.0;
      [self.superview bringSubviewToFront:self];
      if(self.delegate && [self.delegate respondsToSelector:@selector(dragCellItemEnd:)]){
        [self.delegate dragCellItemEnd:self];
      }
      break;
    }
    default:
      break;
  }
}

- (void)_timerAction:(NSTimer *)timer{
  if(self.delegate && [self.delegate respondsToSelector:@selector(dragCellItem:)]){
    [self.delegate dragCellItem:self];
  }
  if ([_moveTimer isValid]) {
    [_moveTimer invalidate];
    self.moveTimer = nil;
  }
}

- (void)addTapTarget:(id)target select:(SEL)selector{
    self.tapDelegate=target;
    self.tapSel=selector;
}

// 重置碰撞检测区域
- (void)setFrame:(CGRect)frame{
  [super setFrame:frame];
  // 更新碰撞区域
  self.crashTestRect = CGRectInset(self.frame, INSET_X, INSET_Y);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
